﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Contrib.Quantcast.Services;
using Orchard.Events;

namespace Contrib.Quantcast.ImportExport
{
    public interface IExportEventHandler : IEventHandler
    {
        void Exporting(dynamic context);
        void Exported(dynamic context);
    }

    public class QuantcastExportHandler : IExportEventHandler
    {
        private readonly ISettingsService _settingsService;

        public QuantcastExportHandler(ISettingsService settingsService)
        {
            _settingsService = settingsService;
        }

        public void Exporting(dynamic context)
        {
        }

        public void Exported(dynamic context)
        {
            if (!((IEnumerable<string>)context.ExportOptions.CustomSteps).Contains(QuantcastCustomExportStep.ExportStep))
            {
                return;
            }

            var settingsRecord = _settingsService.Get();

            if (settingsRecord == null)
                return;

            var googleAnalyics = new XElement(QuantcastCustomExportStep.ExportStep,
                                              new XAttribute("Enabled", settingsRecord.Enable.ToString()));

            context.Document.Element("Orchard").Add(googleAnalyics);

            if (!string.IsNullOrWhiteSpace(settingsRecord.Script))
            {
                googleAnalyics.Value = settingsRecord.Script;
            }
        }
    }
}

